<template>
  <view class="inbound-container">
    
    <!-- 筛选栏 -->
    <view class="filter-bar">
      <!-- 状态分类 -->
      <picker 
        class="filter-picker" 
        mode="selector" 
        :range="statusOptions" 
        @change="onStatusChange"
        :value="statusIndex"
      >
        <view class="filter-item">
          <text class="filter-text">{{ statusOptions[statusIndex] }}</text>
          <text class="filter-arrow">▼</text>
        </view>
      </picker>
      <!-- 仓库分类 -->
      <picker 
        class="filter-picker" 
        mode="selector" 
        :range="warehouseOptions" 
        @change="onWarehouseChange"
        :value="warehouseIndex"
      >
        <view class="filter-item">
          <text class="filter-text">{{ warehouseOptions[warehouseIndex] }}</text>
          <text class="filter-arrow">▼</text>
        </view>
      </picker>
    </view>

    
    <!-- 任务列表 -->
    <scroll-view 
      class="task-list" 
      scroll-y 
      refresher-enabled 
      :refresher-triggered="refreshing"
      refresher-threshold="80"
      refresher-default-style="black"
      @refresherrefresh="onRefresh"
      lower-threshold="50"
      enable-back-to-top
      @scrolltolower="loadMoreTasks">
      <view  class="task-card" v-for="(task, index) in filteredTaskList" :key="index" @click="handleCardClick(task)">
        <!-- 卡片顶部 -->
        <view class="card-header">
          <text class="task-type">任务类型：<text class="task-type-value">{{ task['6864a5824e2949f41199067a'] }}</text></text>
          <text class="status-tag">{{ task['6864a5824e2949f411990679'] }}</text>
        </view>
        
        <!-- 卡片详情 -->
        <view  class="card-details">
        
          <view class="detail-item" v-if="task['6882ed4b2430e5add306a56a'] && task['6882ed4b2430e5add306a56a'].trim() !== ''">
            <text class="detail-label">配送仓点：</text>
            <text class="detail-value">{{ task['68da2273813ea5782ed18db4'] }}</text>
          </view>


          <view class="detail-item">
            <text class="detail-label">SKU 种数：</text>
            <text class="detail-value">{{ Number(task['68b53531153a1d736d85851e']) }}</text>
          </view>

          <view class="detail-item">
            <text class="detail-label">计划总数：</text>
            <text class="detail-value">{{ Number(task['6868db92c66aa1c3b15b032f']) }} 件</text>
          </view>
        
          <view class="detail-item">
            <text class="detail-label">创建人：</text>
            <text class="detail-value">{{ getCreatorName(task) }}</text>
          </view>

          <view class="detail-item">
            <text class="detail-label">创建时间：</text>
            <text class="detail-value">{{ task['68b11ddd823eff0bd6132a73'] || task['ctime'] }}</text>
          </view>
        </view>
        
        <!-- 操作按钮 -->
        <view class="card-actions" v-if="task['6864a5824e2949f411990679'] == '已下发'">
          <text class="cancel-btn" @click.stop="(event) => handleCancel(task, event)">取消</text>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="load-more" v-if="filteredTaskList.length > 0">
        <text class="load-more-text" v-if="loadingMore">正在加载更多...</text>
        <text class="load-more-text" v-else-if="noMoreData">没有更多数据了</text>
        <text class="load-more-text" v-else-if="loadMoreError" @click="loadMoreTasks">加载失败，点击重试</text>
      </view>
    </scroll-view>
    
    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <button class="create-btn" @click="handleCreate">新建任务</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import http from '../../../utils/request'
import { callWorkflowListAPI, callWorkflowAPI, callWorkflowListAPIPaged } from '../../../utils/workflow'
import { useUserStore } from '../../../store/user'
import { useTaskStore } from '../../../store/task'
import { onLoad, onReady, onUnload, onShow, onBackPress } from '@dcloudio/uni-app'

const userStore = useUserStore()
const taskStore = useTaskStore()

// 状态选项
const statusOptions = ref(['全部状态', '已下发', '出库中', '出库完成', '取消出库'])
const statusIndex = ref(0)

// 仓库选项
const warehouseOptions = ref([])
const warehouseIndex = ref(0)

// 处理状态选择变化
const onStatusChange = (e) => {
  statusIndex.value = e.detail.value
  // 筛选条件变化时重置分页
  resetPagination()
  getTaskList()
}

// 处理仓库选择变化
const onWarehouseChange = (e) => {
  warehouseIndex.value = e.detail.value
  // 筛选条件变化时重置分页
  resetPagination()
  getTaskList()
}

// 任务列表数据
const taskList = ref([])

// 分页参数
const pageIndex = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 加载状态
const loading = ref(false)
const loadingMore = ref(false)
const noMoreData = ref(false)
const loadMoreError = ref(false)

// 下拉刷新状态
const refreshing = ref(false)

// 计算属性：过滤后的任务列表
const filteredTaskList = computed(() => {
  // 由于筛选条件已经在API层面处理，这里直接返回任务列表
  return taskList.value || []
})


// 处理取消按钮点击
const handleCancel = (task, event) => {
  // 阻止事件冒泡
  if (event && event.stopPropagation) {
    event.stopPropagation()
  }
  
  uni.showModal({
    title: '提示',
    content: '确定要取消该任务吗？',
    success: async (res) => {
      if (res.confirm) {

       const res = await http.post(`https://www.dachen.vip/api/workflow/hooks/${userStore.getWarehouseInfo().gys_ck_cancel}`, {
    "userRowid": userStore.getUserInfo().rowid,
    "cardRowid": task.rowid
    })

        if(res){
 uni.showToast({
          title: '任务已取消',
          icon: 'success'
        })
          taskStore.setPendingTaskUpdate({ rowid: task.rowid })
        }

       
      }
    }
  })
}

// 处理卡片点击跳转到详情页
const handleCardClick = (task) => {
 uni.navigateTo({
    url: `/pages/warehouse/outbound/detail?rowid=${task.rowid}`
  })
}

// 处理新建任务按钮点击
const handleCreate = () => {
  uni.navigateTo({
    url: '/pages/warehouse/outbound/create'
  })
}

// 根据状态值返回对应的显示文本
const getStatusText = (status) => {
  switch (status) {
    case '已下发':
      return '未出库'
    case '出库中':
      return '出库中'
    case '出库完成':
      return '出库完成'
    case '取消出库':
      return '取消出库'
    default:
      return '未接单'
  }
}

// 安全解析配送仓点名称
const getWarehouseName = (warehouseData) => {
  try {
    if (!warehouseData || warehouseData.trim() === '') {
      return ''
    }
    const parsed = JSON.parse(warehouseData)
    return parsed && parsed[0] && parsed[0].name ? parsed[0].name : ''
  } catch (error) {
    console.error('解析配送仓点数据失败:', error)
    return ''
  }
}

// 安全获取创建人姓名
const getCreatorName = (task) => {
  try {
    // 尝试多种可能的数据结构
    if (task && task.caid && task.caid.fullname) {
      return task.caid.fullname
    }
    if (task && task.caid && typeof task.caid === 'string') {
      // 如果caid是字符串，尝试解析JSON
      const parsed = JSON.parse(task.caid)
      return parsed.fullname || ''
    }
    if (task && task.creator) {
      return task.creator
    }
    return '未知'
  } catch (error) {
    console.error('解析创建人数据失败:', error)
    return '未知'
  }
}

// 下拉刷新处理函数
const onRefresh = async () => {
  refreshing.value = true
  try {
    resetPagination()
    await getTaskList()
  } catch (error) {
    console.error('刷新失败:', error)
  } finally {
    refreshing.value = false
  }
}

const getTaskList = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      refreshing.value = true
    } else {
      loading.value = true
    }
    
    // 构建筛选条件
    const filters = []
    
    // 状态筛选
    if (statusIndex.value > 0 && statusOptions.value[statusIndex.value] !== '全部状态') {
      const statusText = statusOptions.value[statusIndex.value]
      let statusValue = ''
      
      // 根据显示文本映射到实际状态值
      switch (statusText) {
        case '已下发':
          statusValue = '已下发'
          break
        case '出库中':
          statusValue = '出库中'
          break
        case '出库完成':
          statusValue = '出库完成'
          break
        case '取消出库':
          statusValue = '取消出库'
          break
      }
      
      if (statusValue) {
        filters.push({
          "controlId": "6864a5824e2949f411990679",
          "dataType": 30,
          "spliceType": 1,
          "filterType": 2,
          "values": [statusValue]
        })
      }
    }
    
    // 仓库筛选
    if (warehouseIndex.value > 0 && warehouseOptions.value[warehouseIndex.value] !== '全部仓库') {
      const selectedWarehouse = warehouseOptions.value[warehouseIndex.value]
      filters.push({
        "controlId": "68da2273813ea5782ed18db4",
        "dataType": 30,
        "spliceType": 1,
        "filterType": 2,
        "values": [selectedWarehouse]
      })
    }
    
    // 使用分页API获取数据
    const result = await callWorkflowListAPIPaged('ckjhd', filters, pageSize.value, pageIndex.value, 0)
    
    console.log('获取到的任务列表数据:', result)
    console.log('总数据条数:', result.total)
    console.log('当前页数据条数:', result.data ? result.data.length : 0)
    
    if (result && result.data) {
      // 获取用户所属供应商rowid数组
      let userSupplierIds = []
      try {
        const userInfo = userStore.getUserInfo()
        if (userInfo && userInfo['68ea18b6470b6cef2f580870']) {
          userSupplierIds = JSON.parse(userInfo['68ea18b6470b6cef2f580870'])
          console.log('用户所属供应商rowid数组:', userSupplierIds)
        }
      } catch (error) {
        console.error('解析用户供应商信息失败:', error)
      }
      
      // 过滤符合用户供应商的出库单
      let filteredData = result.data
      if (userSupplierIds.length > 0) {
        filteredData = result.data.filter(task => {
          try {
            // 获取出库单的供应商信息
            if (task['6865f64957603df8e65ce6ba']) {
              const supplierData = JSON.parse(task['6865f64957603df8e65ce6ba'])
              if (supplierData && supplierData[0] && supplierData[0].sourcevalue) {
                const supplierInfo = JSON.parse(supplierData[0].sourcevalue)
                const supplierRowId = supplierInfo.rowid
                console.log('出库计划单供应商rowid:', supplierRowId)
                
                // 检查供应商是否在用户的供应商列表中
                return userSupplierIds.includes(supplierRowId)
              }
            }
            return false
          } catch (error) {
            console.error('解析出库单供应商信息失败:', error, task)
            return false
          }
        })
        
        console.log('过滤后的数据条数:', filteredData.length)
      }
      
      if (isRefresh || pageIndex.value === 1) {
        // 刷新或第一页时重置数据
        taskList.value = filteredData
      } else {
        // 加载更多时追加数据
        taskList.value = [...taskList.value, ...filteredData]
      }
      
      totalCount.value = result.total
      
      // 检查是否还有更多数据
      if (result.data.length < pageSize.value || taskList.value.length >= result.total) {
        noMoreData.value = true
      }
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}




const getWarehouseList = async () => {
  try {
    const res = await callWorkflowListAPI('fymbd')
    if(res && res.data){
      console.log('配送仓点', res.data);
      const warehouseNames = res.data.map(item => {
        return item['689b2132f23d51578296f9e6']
      }).filter(name => name && name.trim() !== '') // 过滤空值
      
      // 去重并添加"全部仓库"选项
      const uniqueNames = [...new Set(warehouseNames)]
      warehouseOptions.value = ['全部仓库', ...uniqueNames]
      console.log('仓库选项:', warehouseOptions.value)
    }
  } catch (error) {
    console.error('获取配送仓点失败:', error)
    warehouseOptions.value = ['全部仓库'] // 出错时提供默认值
  }
}

// 重置分页状态
const resetPagination = () => {
  pageIndex.value = 1
  noMoreData.value = false
  loadMoreError.value = false
}

// 上拉加载更多
const loadMoreTasks = () => {
  console.log('加载更多出库任务数据');
  if (loadingMore.value || noMoreData.value || loadMoreError.value) {
    return
  }
  
  // 添加防抖处理，避免频繁触发
  setTimeout(() => {
    loadMoreData()
  }, 300)
}

// 独立的加载更多数据方法
const loadMoreData = async () => {
  try {
    loadingMore.value = true
    loadMoreError.value = false
    
    // 计算下一页的页码
    const nextPageIndex = pageIndex.value + 1
    
    // 构建筛选条件
    const filters = []
    
    // 状态筛选
    if (statusIndex.value > 0 && statusOptions.value[statusIndex.value] !== '全部状态') {
      const statusText = statusOptions.value[statusIndex.value]
      let statusValue = ''
      
      // 根据显示文本映射到实际状态值
      switch (statusText) {
        case '已下发':
          statusValue = '已下发'
          break
        case '出库中':
          statusValue = '出库中'
          break
        case '出库完成':
          statusValue = '出库完成'
          break
        case '取消出库':
          statusValue = '取消出库'
          break
      }
      
      if (statusValue) {
        filters.push({
          "controlId": "6864a5824e2949f411990679",
          "dataType": 30,
          "spliceType": 1,
          "filterType": 2,
          "values": [statusValue]
        })
      }
    }
    
    // 仓库筛选
    if (warehouseIndex.value > 0 && warehouseOptions.value[warehouseIndex.value] !== '全部仓库') {
      const selectedWarehouse = warehouseOptions.value[warehouseIndex.value]
      filters.push({
        "controlId": "68da2273813ea5782ed18db4",
        "dataType": 30,
        "spliceType": 1,
        "filterType": 2,
        "values": [selectedWarehouse]
      })
    }
    
    const result = await callWorkflowListAPIPaged('ckjhd', filters, pageSize.value, nextPageIndex, 0)
    
    if(result && result.data) {
      console.log('加载更多出库任务数据:', result.data)
      
      // 追加数据到现有列表
      if (result.data.length > 0) {
        taskList.value = [...taskList.value, ...result.data]
        // 只有在数据加载成功后才更新页码
        pageIndex.value = nextPageIndex
      }
      
      // 检查是否还有更多数据
      if (result.data.length < pageSize.value || taskList.value.length >= result.total) {
        noMoreData.value = true
      }
      
    } else {
      loadMoreError.value = true
    }
  } catch (error) {
    console.error('加载更多出库任务数据失败:', error)
    loadMoreError.value = true
  } finally {
    loadingMore.value = false
  }
}

onLoad(() => {
  console.log('供应商数组', userStore.getUserInfo()['68ea18b6470b6cef2f580870']);
  
  resetPagination()
  getTaskList()
  getWarehouseList()
})

// 监听任务更新
watch(() => taskStore.pendingTaskUpdate, async (newTask) => {
  if (newTask && newTask.rowid) {
    console.log('检测到待更新任务:', newTask)
 
    // 显示加载动画
    uni.showLoading({
      title: '处理中...',
      mask: true
    })

    try {
      const res = await callWorkflowAPI('ckjhd', newTask.rowid, {}, 1)
      console.log('任务更新响应:', res)
      
      if (res && res.rowid) {
        const index = taskList.value.findIndex(task => task.rowid === newTask.rowid)
        if (index !== -1) {
          const updatedTask = res
          taskList.value[index] = updatedTask
          console.log('任务数据更新成功:', updatedTask)
        }
      }
    } catch (error) {
      console.error('任务更新失败:', error)
      uni.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      })
    } finally {
      uni.hideLoading()
      taskStore.clearPendingTaskUpdate()
    }
  }
  if(newTask && newTask.updata){
   await getTaskList()
  }
})

onUnload(() => {
  // 页面卸载时清理待处理任务
  if (taskStore.pendingTaskUpdate) {
    taskStore.clearPendingTaskUpdate()
  }
})

</script>

<style lang="scss" scoped>
.inbound-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  

  
  // 筛选栏
  .filter-bar {
    background-color: #ffffff;
    padding: 20rpx 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
    
    .filter-picker {
      flex: 1;
      
      .filter-item {
        display: flex;
        align-items: center;
        justify-content: center;
        
        .filter-text {
          color: #999999;
          font-size: 28rpx;
          margin-right: 10rpx;
        }
        
        .filter-arrow {
          color: #999999;
          font-size: 20rpx;
        }
      }
    }
  }
  
  // 任务列表
  .task-list {
    height: calc(100vh - 200rpx);
    
    .load-more {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 30rpx 0;
      
      .load-more-text {
        font-size: 26rpx;
        color: #999;
        
        &:active {
          opacity: 0.7;
        }
      }
    }
    
    .task-card {
      background-color: #ffffff;
      border-radius: 16rpx;
      padding: 30rpx;
      margin: 20rpx;
      box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.15);
      position: relative;
      
      // 卡片顶部
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        .task-type {
          color: #999999;
          font-size: 28rpx;
          
          .task-type-value {
            color: #000000;
            font-weight: bold;
          }
        }
        
        .status-tag {
          color: #87CEEB;
          font-size: 29rpx;
        }
      }
      
      // 卡片详情
      .card-details {
        margin-bottom: 20rpx;
        
        .detail-item {
          display: flex;
          margin-bottom: 10rpx;
          
          .detail-label {
            color: #999999;
            font-size: 26rpx;
            min-width: 140rpx;
          }
          
          .detail-value {
            color: #000000;
            font-size: 26rpx;
            flex: 1;
          }
        }
      }
      
      // 操作按钮
      .card-actions {
        position: absolute;
        bottom: 30rpx;
        right: 30rpx;
        
        .cancel-btn {
          padding: 10rpx 30rpx;
          background-color: #ffffff;
          color: #87CEEB;
          border: 2rpx solid #87CEEB;
          border-radius: 10px;
          font-size: 26rpx;
        }
      }
    }
  }
  
  // 底部操作按钮
  .bottom-actions {
    background-color: #ffffff;
    padding: 30rpx;
    box-shadow: 0 -2rpx 4rpx rgba(0, 0, 0, 0.1);
    
    .create-btn {
      width: 90%;
      background: linear-gradient(to right, #48eceb, #0fcee9);
      color: #ffffff;
      border: none;
      border-radius: 32rpx;
      font-size: 32rpx;
      font-weight: bold;
      margin: 0 auto;
      display: block;
    }
  }
}
</style>